package cn.wangkai.peanut.mvc.admin.dao.manager;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import cn.wangkai.peanut.db.DbFactory;
import cn.wangkai.peanut.db.WKDbException;
import cn.wangkai.peanut.db.iface.IDbFactory;
import cn.wangkai.peanut.db.iface.IMyDb;
import cn.wangkai.peanut.db.manager.ManagerImp;
import cn.wangkai.peanut.mvc.admin.model.Right;
import cn.wangkai.peanut.mvc.admin.model.Roleright;



public class RolerightManagerImp extends ManagerImp<Roleright> implements RolerightManager {
	
	private static final Log loger = LogFactory.getLog(RolerightManagerImp.class);
	public IDbFactory dbFactory = new DbFactory();
	
	public RolerightManagerImp() {
		loger.debug("Begin RoleRightManagerImp");
	}

	public Class<?> getModuleClass(){
		return Roleright.class;
	}
	
	public Roleright findByroleid(IMyDb db,String roleid,String rightid)  throws SQLException, WKDbException{
		String queryString = "SELECT * FROM tb_sus_roleright WHERE ROLEID=? AND RIGHTID=?";
		Roleright roleright = (Roleright) dbFactory.getOne(db, queryString,Roleright.class, roleid,rightid);
		return roleright;
	}
	
	public void del(IMyDb db,String roleid,String rightids)  throws SQLException, WKDbException{
		String querystring = "DELETE FROM tb_sus_roleright WHERE ROLEID=?";
		if(StringUtils.isNotBlank(rightids)){
			querystring = querystring + " AND RIGHTID not in ("+rightids+")";
		}
		dbFactory.execute(db, querystring, roleid);
	}
	
	
	public List<Right> findrole(IMyDb db,String roleid)  throws SQLException, WKDbException{
		ArrayList<Object> params = new ArrayList<Object>();
		StringBuffer SQL = new StringBuffer("SELECT b.* FROM tb_sus_roleright a LEFT JOIN tb_sus_right b on a.RIGHTID=b.RIGHTID ");
		StringBuffer SQLWHERE = new StringBuffer();
		if(StringUtils.isNotEmpty(roleid)){
			SQLWHERE.append(" WHERE a.ROLEID=? ");
			params.add(roleid);
		}else{
			SQLWHERE.append(" WHERE a.ROLEID is NULL ");
		}
		if (SQLWHERE.length() > 0) {
			SQL.append(SQLWHERE);
		}
		SQL.append("order by sid");
		return dbFactory.query(db, SQL.toString(), Right.class,params.toArray());
	}
	
	/**
	 * 
	 * @param args
	 */
	public static void main(String[] args) {

	}
}
